 //
//  WBMainViewController.swift
//  WB
//
//  Created by macssss on 16/6/29.
//  Copyright © 2016年 macssss. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {
    
    //时间定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        setupChildControllers()
        setupComposeButton()
        setupTime()
        //新特性视图
        setupNewFeatureViews()
        
        delegate = self
        
        //注册通知 相当于接收通知信号
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)

        
    }
    
    
    deinit {
        
        //销毁时钟
        timer?.invalidate()
        //注销通知中心
        NotificationCenter.default.removeObserver(self)
        
        
    }
    
    
    @objc private func userLogin(n: Notification) {
        
        print("用户通知\(n)")
        
       var when = DispatchTime.now()
        
        if n.object != nil {
            
            //设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
       
            SVProgressHUD.showInfo(withStatus: "用户登录超时")
            
            //延迟时间
            when = DispatchTime.now() + 2
            
        }
        
        DispatchQueue.main.after(when: when) { 
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let nav = UINavigationController(rootViewController: WBOAthViewController())
            
            self.present(nav, animated: true, completion: nil)
            
        }

    }

    
    //MARK: 设置竖屏
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        
        return .portrait
    }
    
    
    //MARK: 点击按钮监听方法
    
//   @objc private func clickButton() {
//   let vc = UIViewController ()
//    
//    let nav = UINavigationController(rootViewController: vc)
//    
//    present(nav, animated: true, completion: nil)
//    
//    }
    
//    MARK: - 撰写微博
    @objc private func composeStatus() {
        
        let v = WBComposeTypeView.composeTypeVieW()
        
        v.show()
        
    }
    
    
    //MARK: 私有控件 懒加载按钮
    
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
}
 
//MARK: - 判断新特性或者欢迎界面
 extension WBMainViewController {
    
    func setupNewFeatureViews() {
        
        
        //判断用户是否登录
        if !WBNetworkManager.shared.userLogon {
            
            return
        }
        
        //判断是从欢迎还是新特性启动
        let v = isNewVersion ? WBNewFeatureView.newFeatuerView() : WBWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
        
    }
    
    //计算行属性 不占用储存空间
    //构造函数 给属性分配空间
    /**
     版本号
     - 在 AppStore 每次升级应用程序，版本号都需要增加，不能递减
     
     - 组成 主版本号.次版本号.修订版本号
     - 主版本号：意味着大的修改，使用者也需要做大的适应
     - 次版本号：意味着小的修改，某些函数和方法的使用或者参数有变化
     - 修订版本号：框架／程序内部 bug 的修订，不会对使用者造成任何的影响
     */

    private var isNewVersion: Bool {
        
        
        // 1. 取当前的版本号 1.0.2
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)

        // 2. 取保存在 `Document(iTunes备份)[最理想保存在用户偏好]` 目录中的之前的版本号 "1.0.2"
        let path: String = ("version" as String).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print("沙河版本" + sandboxVersion)
        
        // 3. 将当前版本号保存在沙盒 1.0.2
       _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        // 4. 返回两个版本号`是否一致` not new
        return currentVersion != sandboxVersion

    }
 }

//MARK: - 代理方法————UITabBarControllerDelegate

extension WBMainViewController: UITabBarControllerDelegate {
    
    //MARK: - 是否要跳转到 目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换的控制器\(viewController)")
        
        let idex = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idex == selectedIndex {
            
            let nav = childViewControllers[0] as! UINavigationController
            
            let vc = nav.childViewControllers[0] as! WBHomeViewController

            vc.tabelView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
            
            //跳转控制器后 删除小红点
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared().applicationIconBadgeNumber = 0
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}

//MARK: - 时间定时相关方法
extension WBMainViewController {
    
    //MARK: - 定义时钟方法
    private func setupTime() {
        
        timer = Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        
    }
    
    @objc private func updateTime() {
        
        //当token 为空时直接返回
        if !WBNetworkManager.shared.userLogon {
            
            return
        }
        
        
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("监测到有\(count)条未读")
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            UIApplication.shared().applicationIconBadgeNumber = count
        }
    }
    
}

//MARK: -  ToBar中间加号按钮
extension WBMainViewController {
    

    //MARK:添加加号按钮
    private func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        //获得控制器个数
        let count = CGFloat(childViewControllers.count)
        
        //获得tabBar宽度 等分5个按钮
        let addWidth = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * addWidth, dy: 0)
        
        //添加监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //MARK: - 设置所有控制器
    private func setupChildControllers() {
        
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil  {
            
            let path = Bundle.main.pathForResource("main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
            
        }

        
        //获取路径
        guard let array  = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
        
        else {
         return
        }
        
        

        //创建UIViewController数组
        var arrayM = [UIViewController]()
        
        //遍历字典追加到数组中
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
            
        }
        
        viewControllers = arrayM
    }
    
    
    //MARK:设置子控制器
    private func controller(dict:[String: AnyObject]) -> UIViewController {
    
    //守护常量是否有值
        guard let clsName = dict["clsName"] as? String,
            title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
            cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseController.Type,
        visitorsDicts = dict["visitionInfo"] as? [String : String]
            else {
            return UIViewController()
        }
        
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //给访客视图设置信息
        vc.vistorsInfoDict = visitorsDicts
        //设置图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置按钮比字体的颜色 和默认字号
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange()], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        //创建NavigationController
        let nvc = WBNavigationController(rootViewController: vc)
        
        return nvc
        
        
    }
    
}









